package websocket

import (
	// "bufio"
	"code.google.com/p/go.net/websocket"
	"container/list"
	"fmt"
	"github.com/martini-contrib/render"
	"net/http"
	"time"
)

var connid int
var conns *list.List

func ChatroomServer(ws *websocket.Conn) {
	ws.SetDeadline(time.Now().Add(time.Duration(3600) * time.Second)) //设置websocket超时时间，需要做心跳机制保证链接不超时
	fmt.Println(ws.Request().Form)
	var err error
	connid++
	id := connid
	item := conns.PushBack(ws)
	fmt.Printf("connection id: %d : count:%d\n", id, conns.Len())
	for {
		fmt.Println("start")
		var reply string
		if err = websocket.Message.Receive(ws, &reply); err != nil {
			conns.Remove(item)
			fmt.Printf("remove conn:count:%d", conns.Len())
			break
		}

		fmt.Println("received back from client:" + reply)
		msg := "Received : " + reply
		fmt.Println("Sending to cient: " + msg)
		if err = websocket.Message.Send(ws, msg); err != nil {
			conns.Remove(item)
			fmt.Printf("remove conn:count:%d", conns.Len())
			break
		}
	}
}

func Client(r render.Render, res http.ResponseWriter, req *http.Request) {
	r.HTML("test/websocket/test.html", map[string]interface{}{})
}

func init() {
	connid = 0
	conns = list.New()
	// fmt.Printf(`Welcome chatroom server! `)

	// http.Handle("/websocket/send", websocket.Handler(ChatroomServer))
	// http.HandleFunc("/websocket", Client)
	// go func() {
	// 	err := http.ListenAndServe(":9090", nil)
	// 	if err != nil {
	// 		panic("ListenAndServe: " + err.Error())
	// 	}
	// }()

	//无需路由的websocket
	// fmt.Printf(`Welcome chatroom server! `)
	// connid = 0
	// conns = list.New()
	// http.HandleFunc("/", Client)

	// go func() {
	// 	err := http.ListenAndServe(":9090", websocket.Server{websocket.Config{}, nil, ChatroomServer})
	// 	if err != nil {
	// 		panic("ListenAndServe: " + err.Error())
	// 	}
	// }()
	// err := http.ListenAndServe(":9091", nil)
	// if err != nil {
	// 	panic("ListenAndServe: " + err.Error())
	// }
}
